package com.aqie.meet.ui.friend;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aqie.libcommon.adapter.CommonAdapter2;
import com.aqie.libcommon.adapter.CommonViewHolder2;
import com.aqie.libcommon.app.BaseApplication;
import com.aqie.libcommon.app.BaseFragment;
import com.aqie.libcommon.utils.CommonUtils;
import com.aqie.libcommon.utils.SimpleJsonTool;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.friend.FriendListModel;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.libnavanotation.FragmentDestination;
import com.aqie.meet.R;
import com.aqie.meet.ui.chat.MessageActivity;
import com.aqie.meet.ui.login.AccountActivity;
import com.aqie.meet.ui.my.FriendHomePageActivity;
import com.aqie.meet.ui.search.SearchActivity;
import com.aqie.meet.utils.Utils;
import com.aqie.meet.view.AImageView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import circletextimage.viviant.com.circletextimagelib.view.CircleTextImage;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@FragmentDestination(pageUrl = "main/tabs/friend", asStarter = false,needLogin = true)
public class FriendFragment extends BaseFragment{

    private FriendViewModel mViewModel;

    public static FriendFragment newInstance() {
        return new FriendFragment();
    }

    @BindView(R.id.friend_request_recycler_view)
    RecyclerView mFriendRequestRecycleView;
    @BindView(R.id.new_friend)
    LinearLayout mNewFriendLinerLayout;

    @BindView(R.id.friend_recommended_recycler_view)
    RecyclerView mFriendRecommendedRecycleView;

    @BindView(R.id.friend_recycler_view)
    RecyclerView mFriendRecycleView;

    @BindView(R.id.im_search)
    ImageView mSearch;

    private List<User> mRequestFriends = new ArrayList<>();
    private List<User> mRecommendedFriends = new ArrayList<>();
    private List<User> mFriends = new ArrayList<>();

    private CommonAdapter2<User> mRequestFriendsAdapter;
    private CommonAdapter2<User> mRecommendedFriendsAdapter;
    private CommonAdapter2<User> mFriendsAdapter;

    @Override
    protected int getContentLayoutId() {
        return R.layout.friend_fragment;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        initView();
    }

    // 注意修改渲染数据
    private void initView() {
        // 新的朋友
        mFriendRequestRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mFriendRequestRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mRequestFriendsAdapter = new CommonAdapter2<>(mRequestFriends, new CommonAdapter2.OnBindDataListener<User>() {
            @Override
            public void onBindViewHolder(User model, CommonViewHolder2 viewHolder, int type, int position) {
                fillData(model, viewHolder);
                // 同意好友请求
                viewHolder.getView(R.id.btn_pass_friend).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // BaseApplication.showToast("添加好友");
                        Log.e(TAG, "position" + position);
                        agreeFriend(model.getUserId(), position);

                    }
                });
                viewHolder.getView(R.id.btn_reject_friend).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // BaseApplication.showToast("添加好友");
                        rejectFriend(model.getUserId(), position);
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.friend_request_item;
            }
        });
        mFriendRequestRecycleView.setAdapter(mRequestFriendsAdapter);

        // 推荐好友
        mFriendRecommendedRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mFriendRecommendedRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mRecommendedFriendsAdapter = new CommonAdapter2<>(mRecommendedFriends, new CommonAdapter2.OnBindDataListener<User>() {
            @Override
            public void onBindViewHolder(User model, CommonViewHolder2 viewHolder, int type, int position) {
                if(model.isBoolFriend()){
                    viewHolder.goneIfEmpty(R.id.btn_add_friend);
                }else {
                    viewHolder.goneIfEmpty(R.id.btn_added_friend);
                }
                fillData(model, viewHolder);
                // 发送添加好友请求
                viewHolder.getView(R.id.btn_add_friend).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // BaseApplication.showToast("添加好友");
                        addFriend(model.getUserId());
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.friend_recommended_item;
            }
        });
        mFriendRecommendedRecycleView.setAdapter(mRecommendedFriendsAdapter);

        // 我的好友
        mFriendRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mFriendRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mFriendsAdapter = new CommonAdapter2<>(mFriends, new CommonAdapter2.OnBindDataListener<User>() {
            @Override
            public void onBindViewHolder(User model, CommonViewHolder2 viewHolder, int type, int position) {
                fillData(model, viewHolder);

                // 跳转聊天
                viewHolder.getView(R.id.btn_send_message).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.e(TAG, "position " + position + " " + model.getUserId());
                        MessageActivity.show(getActivity(), model.getUserId(), model.getUsername(), true);
                    }
                });
                // 跳转详情
                viewHolder.getView(R.id.avatar).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), FriendHomePageActivity.class);
                        intent.putExtra("talentsId", model.getUserId());
                        startActivity(intent);
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.friend_item;
            }
        });
        mFriendRecycleView.setAdapter(mFriendsAdapter);

    }

    private void agreeFriend(String friendId, int position) {
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.friendRequestAgree(friendId,null);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();
                /*if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }*/
                if(body !=null && body.success()){
                    BaseApplication.showToast("同意成功");
                    getFriend();
                    // 更新界面
                    mRequestFriends.remove(position);
                    mRequestFriendsAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {

            }
        });
    }

    private void rejectFriend(String friendId, int position) {
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.friendRequestRefuse(friendId);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();
                /*if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }*/
                if(body !=null && body.success()){
                    BaseApplication.showToast("拒绝成功");
                    getFriend();
                    // 更新界面
                    mRequestFriends.remove(position);
                    mRequestFriendsAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {

            }
        });
    }

    private void fillData(User model, CommonViewHolder2 viewHolder) {
        CircleTextImage mCircleTextImage = viewHolder.getView(R.id.friend_avatar);
        AImageView mTrueAvatar = viewHolder.getView(R.id.tag_avatar_true);
        if(model != null && model.getAvatar() != null){
            mTrueAvatar.setVisibility(View.VISIBLE);
            mTrueAvatar.setImageUrl(model.getAvatar());
            mCircleTextImage.setVisibility(View.GONE);
        } else {
            // 用户名不为空展示文字头像
            if(model != null && model.getUsername() != null && model.getUsername().length() > 0){
                mCircleTextImage.setText4CircleImage(Utils.getName(model.getUsername()));
            }
        }

        viewHolder.setText(R.id.friend_name, model.getUsername() + " | " + model.getTrade() + " " + model.getPosition());
        viewHolder.setText(R.id.friend_desc, model.getCity() + " " + model.getWorkingYears() + "年工作经验");
        if(TextUtils.isEmpty(model.getCity()) || model.getWorkingYears() == null ){
            viewHolder.goneIfEmpty(R.id.friend_desc);
        }

        viewHolder.setText(R.id.et_resource, model.getAnswerOne());
        viewHolder.setText(R.id.et_need, model.getAnswerTwo());
        viewHolder.setText(R.id.et_know, model.getAnswerThree());

        viewHolder.getView(R.id.friend_name).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.toggle(R.id.setting_about_content);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        getFriend();
    }

    private void addFriend(String friendId) {
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.friendRequestSend(friendId,null,null);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {
                RspModel<Boolean> body = response.body();
                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    BaseApplication.showToast("发送成功");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {

            }
        });
    }

    private void getFriend() {
        RemoteService service = Network.remote();
        Call<RspModel<FriendListModel>> call = service.friend();
        call.enqueue(new Callback<RspModel<FriendListModel>>() {
            @Override
            public void onResponse(Call<RspModel<FriendListModel>> call, Response<RspModel<FriendListModel>> response) {
                RspModel<FriendListModel> body = response.body();
                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    FriendListModel friend = body.getData();
                    String rspString = SimpleJsonTool.toJson(friend); Log.e(TAG, rspString);
                    // 新朋友
                    if(friend.getRequestFriends().size() == 0) {
                        mFriendRequestRecycleView.setVisibility(View.VISIBLE);
                        mNewFriendLinerLayout.setVisibility(View.VISIBLE);
                    } else {
                        mFriendRequestRecycleView.setVisibility(View.VISIBLE);
                        mNewFriendLinerLayout.setVisibility(View.VISIBLE);
                        if (mRequestFriends.size() > 0) {
                            mRequestFriends.clear();
                        }
                        mRequestFriends.addAll(friend.getRequestFriends());
                        mRequestFriendsAdapter.notifyDataSetChanged();
                        Log.e(TAG, "newFriend list:" + mRequestFriends.toString());
                    }
                    // 推荐朋友
                    if(friend.getRecommendedFriends().size() == 0) {
                        mFriendRecommendedRecycleView.setVisibility(View.GONE);
                    } else {
                        mFriendRecommendedRecycleView.setVisibility(View.VISIBLE);
                        if (mRecommendedFriends.size() > 0) {
                            mRecommendedFriends.clear();
                        }
                        mRecommendedFriends.addAll(friend.getRecommendedFriends());
                        mRecommendedFriendsAdapter.notifyDataSetChanged();
                        Log.e(TAG, "RecommendedFriend list:" + mRecommendedFriends.toString());
                    }

                    // 朋友
                    if(friend.getFriends().size() == 0) {
                        mFriendRecycleView.setVisibility(View.GONE);
                    } else {
                        mFriendRecycleView.setVisibility(View.VISIBLE);
                        if (mFriends.size() > 0) {
                            mFriends.clear();
                        }
                        mFriends.addAll(friend.getFriends());
                        mFriendsAdapter.notifyDataSetChanged();
                        Log.e(TAG, "Friend list:" + mFriends.toString());
                    }
                }else {
                    Log.e(TAG, "request fail: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<RspModel<FriendListModel>> call, Throwable t) {
                Log.e(TAG, "request fail: onFailure");
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(FriendViewModel.class);
        // TODO: Use the ViewModel
    }

    // 好友申请列表
    @OnClick(R.id.new_friend_more)
    void friendRequestMode(){
        startActivity(new Intent(getActivity(), FriendRequestListActivity.class));
    }

    // 推荐好友列表
    @OnClick(R.id.recommend_friend_more)
    void recommendFriendMore(){
        startActivity(new Intent(getActivity(), RecommendFriendActivity.class));
    }

    // 好友列表
    /*@OnClick(R.id.my_friend_more)
    void myFriendMore(){
        startActivity(new Intent(getActivity(), FriendListActivity.class));
    }*/


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (!CommonUtils.isEmpty(mRequestFriends)) {
                getFriend();
            }
        }
    }

    // 点击搜索人才按钮
    @OnClick(R.id.im_search)
    void onSearchMenuClick() {
        SearchActivity.show(getActivity(), SearchActivity.TYPE_FRIEND);
    }

}